package z_mxsTest.testToolBackupFiles;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class backupFileTool {
    private static final int BUTTON_SIZE = 150;
    private static final int HORIZONTAL_SPACING = 200;
    private static final String CONFIG_FILE = "backup_config.properties";
    
    private static Properties config = new Properties();

    public static void main(String[] args) {
        // 加载配置文件
        loadConfig();
        
        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setSize(1024, 768);
        shell.setText("backupFileTool_MXS_V1.0.0");
        shell.setLayout(new GridLayout(1, false));

        // 创建主内容区域
        Composite contentArea = new Composite(shell, SWT.NONE);
        contentArea.setLayout(new GridLayout(1, false));
        contentArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

        // 创建按钮区域
        Composite buttonContainer = new Composite(contentArea, SWT.NONE);
        buttonContainer.setLayout(new GridLayout(2, true));
        GridData buttonContainerData = new GridData(SWT.FILL, SWT.TOP, true, false);
        buttonContainerData.heightHint = shell.getSize().y / 3;
        buttonContainer.setLayoutData(buttonContainerData);
        ((GridLayout) buttonContainer.getLayout()).horizontalSpacing = HORIZONTAL_SPACING;

        // 创建路径输入区域（修改为3列布局）
        Composite pathInputArea = new Composite(contentArea, SWT.NONE);
        GridLayout pathLayout = new GridLayout(3, false);
        pathInputArea.setLayout(pathLayout);
        GridData pathInputData = new GridData(SWT.FILL, SWT.FILL, true, true);
        pathInputArea.setLayoutData(pathInputData);

        // 创建字体
        Font largeButtonFont = new Font(display, "Arial", 16, SWT.NORMAL); // Backup/Restore按钮字体
        Font smallButtonFont = new Font(display, "Arial", 8, SWT.NORMAL);  // 其他按钮字体

        // 源路径标签、输入框和浏览按钮
        Label srcLabel = new Label(pathInputArea, SWT.NONE);
        srcLabel.setText("源路径:");
        srcLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));

        Text srcPathText = new Text(pathInputArea, SWT.BORDER);
        srcPathText.setText(config.getProperty("source.dir", ""));
        srcPathText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

        Button srcBrowseBtn = new Button(pathInputArea, SWT.PUSH);
        srcBrowseBtn.setText("浏览...");
        srcBrowseBtn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
        srcBrowseBtn.setFont(smallButtonFont);

        // 目标路径标签、输入框和浏览按钮
        Label desLabel = new Label(pathInputArea, SWT.NONE);
        desLabel.setText("目标路径:");
        desLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));

        Text desPathText = new Text(pathInputArea, SWT.BORDER);
        desPathText.setText(config.getProperty("target.dir", ""));
        desPathText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

        Button desBrowseBtn = new Button(pathInputArea, SWT.PUSH);
        desBrowseBtn.setText("浏览...");
        desBrowseBtn.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
        desBrowseBtn.setFont(smallButtonFont);

        // 创建保存配置按钮（跨3列）
        Button saveConfigBtn = new Button(pathInputArea, SWT.PUSH);
        saveConfigBtn.setText("保存配置");
        GridData saveBtnData = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
        saveBtnData.horizontalSpan = 3;
        saveConfigBtn.setLayoutData(saveBtnData);
        saveConfigBtn.setFont(smallButtonFont);

        // 创建底部区域
        Composite bottomArea = new Composite(contentArea, SWT.NONE);
        bottomArea.setLayout(new GridLayout(1, false));
        GridData bottomData = new GridData(SWT.FILL, SWT.BOTTOM, true, false);
        bottomData.heightHint = shell.getSize().y / 5;
        bottomArea.setLayoutData(bottomData);

        // 创建状态栏
        Text statusBar = new Text(bottomArea, SWT.READ_ONLY | SWT.BORDER);
        statusBar.setText("就绪");
        statusBar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));

        // 源路径浏览按钮事件
        srcBrowseBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                DirectoryDialog dialog = new DirectoryDialog(shell, SWT.OPEN);
                dialog.setText("选择源目录");
                dialog.setFilterPath(srcPathText.getText());
                String selectedDir = dialog.open();
                if (selectedDir != null) {
                    srcPathText.setText(selectedDir);
                }
            }
        });

        // 目标路径浏览按钮事件
        desBrowseBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                DirectoryDialog dialog = new DirectoryDialog(shell, SWT.OPEN);
                dialog.setText("选择目标目录");
                dialog.setFilterPath(desPathText.getText());
                String selectedDir = dialog.open();
                if (selectedDir != null) {
                    desPathText.setText(selectedDir);
                }
            }
        });

        // 保存配置按钮事件
        saveConfigBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                saveConfig(srcPathText.getText(), desPathText.getText());
                MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                msgBox.setText("配置保存成功");
                msgBox.setMessage("配置已保存到 " + CONFIG_FILE);
                msgBox.open();
            }
        });

        // 创建左侧按钮
        Composite leftContainer = createSideContainer(buttonContainer);
        Button btnBackup = createBackupButton(leftContainer, statusBar, srcPathText, desPathText);
        btnBackup.setFont(largeButtonFont);

        // 创建右侧按钮
        Composite rightContainer = createSideContainer(buttonContainer);
        Button btnRestore = createRestoreButton(rightContainer, statusBar, srcPathText, desPathText);
        btnRestore.setFont(largeButtonFont);

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        // 释放字体资源
        largeButtonFont.dispose();
        smallButtonFont.dispose();
        display.dispose();
    }

    private static void loadConfig() {
        try {
            Path configPath = Paths.get(CONFIG_FILE);
            if (Files.exists(configPath)) {
                config.load(Files.newInputStream(configPath));
            }
        } catch (IOException e) {
            System.err.println("加载配置文件失败: " + e.getMessage());
        }
    }

    private static void saveConfig(String srcPath, String desPath) {
        try {
            config.setProperty("source.dir", srcPath);
            config.setProperty("target.dir", desPath);
            config.store(Files.newOutputStream(Paths.get(CONFIG_FILE)), 
                         "Backup Tool Configuration - Last updated: " + new Date());
        } catch (IOException e) {
            System.err.println("保存配置文件失败: " + e.getMessage());
        }
    }

    private static Composite createSideContainer(Composite parent) {
        Composite container = new Composite(parent, SWT.NONE);
        container.setLayout(new GridLayout(1, false));
        container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        return container;
    }

    private static Button createBackupButton(Composite container, Text statusBar, Text srcPathText, Text desPathText) {
        Button btnBackup = new Button(container, SWT.PUSH);
        btnBackup.setText("Backup");

        GridData data = new GridData(SWT.CENTER, SWT.CENTER, true, true);
        data.widthHint = BUTTON_SIZE;
        data.heightHint = BUTTON_SIZE;
        btnBackup.setLayoutData(data);

        btnBackup.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String srcPath = srcPathText.getText();
                String desPath = desPathText.getText();
                
                if (srcPath.isEmpty() || desPath.isEmpty()) {
                    statusBar.setText("错误: 源路径和目标路径不能为空");
                    return;
                }
                
                try {
                    statusBar.setText("正在备份文件...");
                    copyDirectory(Paths.get(srcPath), Paths.get(desPath));
                    statusBar.setText("备份成功 - " + getCurrentTime());
                } catch (IOException ex) {
                    statusBar.setText("备份失败: " + ex.getMessage());
                    ex.printStackTrace();
                }
            }
        });
        return btnBackup;
    }

    private static Button createRestoreButton(Composite container, Text statusBar, Text srcPathText, Text desPathText) {
        Button btnRestore = new Button(container, SWT.PUSH);
        btnRestore.setText("Restore");

        GridData data = new GridData(SWT.CENTER, SWT.CENTER, true, true);
        data.widthHint = BUTTON_SIZE;
        data.heightHint = BUTTON_SIZE;
        btnRestore.setLayoutData(data);

        btnRestore.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String srcPath = desPathText.getText();
                String desPath = srcPathText.getText();
                
                if (srcPath.isEmpty() || desPath.isEmpty()) {
                    statusBar.setText("错误: 源路径和目标路径不能为空");
                    return;
                }
                
                try {
                    statusBar.setText("正在恢复文件...");
                    copyDirectory(Paths.get(srcPath), Paths.get(desPath));
                    statusBar.setText("恢复成功 - " + getCurrentTime());
                } catch (IOException ex) {
                    statusBar.setText("恢复失败: " + ex.getMessage());
                    ex.printStackTrace();
                }
            }
        });
        return btnRestore;
    }

    private static void copyDirectory(Path source, Path target) throws IOException {
        Files.walk(source)
             .forEach(sourcePath -> {
                 try {
                     Path targetPath = target.resolve(source.relativize(sourcePath));
                     if (Files.isDirectory(sourcePath)) {
                         Files.createDirectories(targetPath);
                     } else {
                         Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                     }
                 } catch (IOException e) {
                     throw new RuntimeException(e);
                 }
             });
    }

    private static String getCurrentTime() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date());
    }
}